package cl.uchile.cos.persistance;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cl.uchile.cos.sync.Message;

public class BasicEventStateManager extends AbstractStateManager {
	private Map<String, List<Message>> events;
	private Map<String, Message> states;

	public BasicEventStateManager() {
		super();
		events = new LinkedHashMap<String, List<Message>>();
		states = new LinkedHashMap<String, Message>();
	}

	@Override
	public void processMessage(Message message) {
		String objectId = message.getObjectId();
		switch (message.getMessageType()) {
		case EVENT:
			if (!events.containsKey(objectId)) {
				events.put(objectId, new LinkedList<Message>());
			}
			events.get(objectId).add(message);
			break;
		case STATE:
			states.put(objectId, message);
			if (events.containsKey(objectId)) {
				events.get(objectId).clear();
			}
			break;

		}

	}

	@Override
	public List<Message> getPersistedState(String objectId) {
		ArrayList<Message> results=new ArrayList<Message>();
		if (states.containsKey(objectId)) {
			results.add(states.get(objectId));
		}
		if (events.containsKey(objectId)) {
			for (Message message : events.get(objectId)) {
				results.add(message);
			}
		}
		return results;

	}

	@Override
	public void persist() {
		// TODO persistir lista de eventos
		
	}


}
